package com.bum.rss.site;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.InitializingBean;

import com.bum.rss.exp.om.RssEntry;
import com.bum.rss.site.cat.BaomoiCat;
import com.bum.rss.site.util.BaseParser;

public class BaomoiSite extends Site implements BaomoiCat, InitializingBean {
	final HashMap<String, String>	CAT_CODES	= new HashMap<String, String>();
	final List<RssEntry>			CATEGORIES	= new ArrayList<RssEntry>(CATS.length);
	final List<RssEntry>			SRC_CATS	= new ArrayList<RssEntry>(SRCS.length);

	@Override
	public void afterPropertiesSet() throws Exception {
		for (int n = CATS.length, i = 0; i < n; i++) {
			CAT_CODES.put(CATS[i][0], CATS[i][2]);
			CATEGORIES.add(new RssEntry(getCode() + URL_SEPARATOR + CATS[i][0], CATS[i][1]));
		}

		for (int i = 0; i < SRCS.length; i++) {
			SRC_CATS.add(new RssEntry(getCode() + URL_SEPARATOR + SRC_CAT + "-" + SRCS[i][0], SRCS[i][1]));
		}
	}

	@Override
	public List<RssEntry> listSiteCats(String user) {
		return CATEGORIES;
	}

	@Override
	public List<RssEntry> listCatEntrys(String cat, String user) {
		if (SRC_CAT.equals(cat)) {
			return new ArrayList<RssEntry>(SRC_CATS);
		}

		return listLinkFromWap(cat);
	}

	public static final String	BAOMOI_URL	= "http://m.baomoi.com/";
	static final int			PAGE_SIZE	= 10;
	static final int			MAX_PAGE	= 50;

	private List<RssEntry> listLinkFromWap(String cat) {
		int page = 1;
		if (cat.indexOf(PAGE_SEPARATOR) > 0) {
			String[] parts = StringUtils.split(cat, PAGE_SEPARATOR);
			page = NumberUtils.toInt(parts[1], 1);
			cat = parts[0];
		}

		String url = null;
		if (CAT_CODES.containsKey(cat)) {
			// http://m.baomoi.com/Home/mostrecent/AmNhac/p/2.epi
			url = BAOMOI_URL + CAT_CODES.get(cat) + "/p/" + page + ".epi";
		} else if (cat.startsWith(SRC_CAT)) {
			// http://m.baomoi.com/Source/a/91/p/2.epi
			String srcCode = cat.substring(cat.indexOf("-") + 1);
			url = BAOMOI_URL + "Source/a/" + srcCode + "/p/" + page + ".epi";
		}

		if (StringUtils.isBlank(url)) {
			return null;
		}

		List<RssEntry> entries = parseRawCat(url, cat);

		if (CollectionUtils.isEmpty(entries)) {
			return null;
		}

		if (entries.size() >= PAGE_SIZE && page < MAX_PAGE) {
			entries.add(new RssEntry(getCode() + URL_SEPARATOR + cat + PAGE_SEPARATOR + (page + 1), NEXT_PAGE_TITLE));
		}

		if (page > 1) {
			entries.add(0, new RssEntry(getCode() + URL_SEPARATOR + cat + PAGE_SEPARATOR + (page - 1), PREV_PAGE_TITLE));
		}

		return entries;
	}

	private static final String[]	INTRO_TRACE	= new String[] {
			"<span class='date'>", "</span> -"
												};

	public List<RssEntry> parseRawCat(String url, String cat) {
		String html = BaseParser.loadHtml(url, BaseParser.IPHONE_HEADERS, true);
		if (StringUtils.isBlank(html)) {
			return null;
		}
		html = html.replace("\"", "'");

		String startToken = "<ul class='listing'><li class='story'>";
		String endToken = "</li></ul></div>";

		html = BaseParser.parseContent(html, startToken, endToken);
		if (StringUtils.isBlank(html)) {
			return null;
		}

		List<RssEntry> entries = new LinkedList<RssEntry>();

		String[] items = html.split("<li class='story'>");
		for (String item : items) {
			String title = BaseParser.parseContent(item, "class='title'>", "</span>");
			String link = BaseParser.parseContent(item, "<a href='", "' class='slink'>");

			title = StringUtils.trimToNull(title);
			link = StringUtils.trimToNull(link);
			if (title == null || link == null) {
				continue;
			}
			link = getRssLink(link, cat);
			if (link == null) {
				continue;
			}

			String imgSrc = BaseParser.parseContent(item, "<img src='", "' alt=");
			if (StringUtils.isNotBlank(imgSrc)) {
				imgSrc = imgSrc.replaceAll("/\\d+/\\d+/", "/");
			}
			String intro = BaseParser.traceBetween(item, INTRO_TRACE, "</span>").trim();

			if (StringUtils.isNotBlank(intro)) {
				int idx = intro.indexOf(" - ");
				if (idx > 0) {
					intro = intro.substring(idx + 3);
				}
			}

			RssEntry entry = new RssEntry();
			entry.setTitle(title);
			entry.setUrl(link);
			entry.setIntro(intro);
			entry.setThumb(imgSrc);

			entries.add(entry);
		}

		return entries;
	}

	@Override
	public RssEntry loadEntry(String path, String user) {
		String url = "http://m.baomoi.com/Home/a/a/a/" + path + ".epi";

		String html = BaseParser.loadHtml(url, BaseParser.IPHONE_HEADERS, true);
		if (StringUtils.isBlank(html)) {
			return null;
		}

		html = html.replace("\"", "'");

		String[] endTokens = {
				"<div class='AkaDigital'", "<div class='related'"
		};
		String endToken = endTokens[0];
		for (String str : endTokens) {
			if (html.contains(str)) {
				endToken = str;
				break;
			}
		}
		html = BaseParser.parseContent(html, "</a></span></p> </div> ", endToken);

		String title = BaseParser.parseContent(html, "<h1>", "</h1>");
		html = BaseParser.parseContent(html, "<p class='summary'>", null);
		if (StringUtils.isNotBlank(html)) {
			int idx = html.indexOf(" - ");
			if (idx > 0 && idx < 40) {
				html = html.substring(idx + 3).trim();
			}
		}

		RssEntry entry = new RssEntry();
		entry.setTitle(title);
		entry.setContent(html);
		return entry;
	}

	@Override
	public String getRssLink(String httpLink) {
		return getRssLink(httpLink, "m");
	}

	/**
	 * http://m.baomoi.com/Home/ThietBi-PhanCung/baodautu.vn/Anh-chinh-thuc-Leica-C-va-phu-kien/11903467.epi thành <br/>
	 * rss://baomoi/cat/11903467
	 */
	protected String getRssLink(String httpLink, String catId) {
		int idx = httpLink.lastIndexOf("/");
		if (idx < 0) {
			return null;
		}

		String id = httpLink.substring(idx + 1, httpLink.indexOf(".epi"));
		if (StringUtils.isBlank(id)) {
			return null;
		}

		return MessageFormat.format("{0}/{1}/{2}", getCode(), catId, id);
	}

	public static void main(String[] args) {
		String path = "14006171";
		Site site = new BaomoiSite();
		RssEntry entry = site.loadEntry(path, null);
		System.out.println(entry.getTitle() + " \n \n " + entry.getContent());
	}
}
